# -*- coding: utf-8 -*-            
# @Author : HJH
# @Time : 2024/4/9 8:39
# @Use :
import base64
import gzip
import hashlib
import json
import random
import time
from datetime import datetime

import requests
import urllib3
from loguru import logger
from requests.adapters import HTTPAdapter

accounts = [{
    'uid': 'HNYC2B',
    'sid': 'CGO8146',
    'key': '806JVH5QC',
    'acc': 'CGO0070'
},
    #     {
    #     'uid': 'SHYA2B',
    #     'sid': 'SHA7026',
    #     'key': 'G0TODRZ49',
    #     'acc': 'SHA0394'
    # }
]
# 增加池子的大小
http = urllib3.PoolManager(num_pools=100)
session = requests.Session()
# 增加重试连接次数
session.mount('http://', HTTPAdapter(max_retries=5))
session.mount('https://', HTTPAdapter(max_retries=5))
# 关闭多余连接
session.keep_alive = False
# 取消验证证书
session.verify = False
# 关闭在设置了verify=False后的错误提示
urllib3.disable_warnings()


def ungzip_base64_encoded_data(encoded_data):
    # 解码Base64数据
    decoded_data = base64.b64decode(encoded_data)
    # 解压缩gzip数据
    ungzipped_data = gzip.decompress(decoded_data).decode('utf-8')
    return ungzipped_data


def get_echo_token(uid, secret):
    try:
        current_date = datetime.now().strftime('%Y%m%d')
        # 生成秘钥，根据ID: 动态分配(uid客户代码)，日期20190413，私钥：_动态分配的私钥（KEY），组合而成
        key = f"{uid}_{current_date}_{secret}"
        return encrypt(key)
    except Exception as e:
        # 处理异常情况
        print(f"【南航ndc 加解密异常】: {e}")
        return ""


def encrypt(key_str):
    sha = None
    try:
        sha1_hash = hashlib.sha1(key_str.encode()).digest()
        sha = int.from_bytes(sha1_hash, byteorder='big', signed=True)
    except Exception as e:
        print(e)
    return str(sha) if sha is not None else ""


def air_shopping(dep, arr, dep_date):
    account = random.choice(accounts)
    uid = account.get('uid')
    sid = account.get('sid')
    key = account.get('key')
    acc = account.get('acc')

    echo_token = get_echo_token(uid, key)

    params = {
        "memberInfo": {
            "accountNumber": acc,
            "agencyID": uid
        },
        "payloadAttributes": {
            "airlineCode": "CZ",
            "channel": "NDC",
            "echoTokenText": echo_token,
            "system": "B2B",
            "timestamp": datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f')[:-3],
            "transactionID": "999999"
        },
        "request": {
            "bigClientId": "20230426",
            "directOnly": True,
            "originDestinations": [{
                "destCityCode": arr,
                "origCityCode": dep,
                "travelDate": dep_date.replace('-', '')
            }],
            "travelers": [{
                "passengerNumber": 1,
                "passengerType": "ADT"
            }]
        }
    }

    header = {
        "zone": "DOM",
        "uid": uid,
        "token": echo_token,
        "channel": "NDC",
        "airline": "CZ",
        "sid": sid
    }

    url = 'http://b2b.airndc.com:31830/hub2-api/ndc/airShopping'

    retry_limit = 5
    retry_count = 0
    while retry_count < retry_limit:
        try:
            response = requests.post(url=url, headers=header, json=params, timeout=10)
            if response.text is not None and response.text != '':
                res_json = ungzip_base64_encoded_data(response.text)
                res_data = json.loads(res_json)
                if res_data.get('status').get('status') == 'SUCCESS':
                    logger.info(f'【{dep}-->{arr} {dep_date} completed... ...】')
                    return res_data.get('response')
                else:
                    message = res_data.get('status').get('errorMessage')
                    logger.error(f'【{dep}-->{arr} {dep_date} {message}】')
                    return None
        except requests.exceptions.Timeout:
            retry_count += 1
            logger.warning(f"Request timed out. Retrying ({retry_count}/{retry_limit})...")
            time.sleep(1)  # 可以加上延时避免过于频繁请求

    if retry_count == retry_limit:
        return None


if __name__ == '__main__':
    # get_echo_token(uid, key)
    res_data = air_shopping('SZX', 'WUH', '2024-08-02')
    print(json.dumps(res_data))
